<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <div id="root">

    </div>
</body>
<script src="../react@17.js"></script>
<script src="../react-dom@17.js"></script>
<script src="../babel.js"></script>
<script type="text/babel">
    // 创建上下文对象 供应商对象
    let Context = React.createContext();
    console.log(Context)
    class App extends React.Component {
        state={
            name:""
        }
        render() {
            return (
                <div>
                    {
                        //使用供应商组件包裹子组件 Provider  供应商 必须绑定value属性，value属性用来给任意一个消费者提供数据
                    }
                    <Context.Provider value={{num:"100g",getName:(name)=>{
                        console.log(name)
                        this.setState({
                            name:name
                        })
                    },name:this.state.name}}>
                        <One />
                        <Two />
                    </Context.Provider>
                </div>
            )
        }
    }
    class One extends React.Component {
        state={
            name:"张三"
        }
        render() {
            return (
                /* 
                    消费者组件，注意 消费者组件内容必须为一个回调函数，作用就是为了获取服务商提供得数据
                */
                <Context.Consumer>
                    {
                        (value) => {
                            console.log(value)
                            return (
                                <div>
                                    <h1>Two组件----{value.num}</h1>
                                    <button onClick={()=>{
                                        value.getName(this.state.name)
                                    }}>向另一个组件传参</button>
                                </div>
                            )
                        }
                    }
                </Context.Consumer>
            )
        }
    }
    class Two extends React.Component {
        render() {
            return (
                <Context.Consumer>
                    {
                        (value) => {
                            return (
                                <div>
                                    <h1>one组件----{value.num}----{value.name}</h1>
                                </div>
                            )
                        }
                    }
                </Context.Consumer>

            )
        }
    }
    ReactDOM.render(<App />, document.getElementById("root"))
</script>

</html>